package com.foreveross.fastdfs;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;


public class FastDFSManager {

	private static Logger logger = Logger.getLogger(FastDFSManager.class);
	public static final String CLIENT_CONFIG_FILE   = "fdfs_client_self.conf";
	public static final String path = FastDFSManager.class.getClassLoader().getResource(CLIENT_CONFIG_FILE).getPath();
	
	private static TrackerClient  trackerClient;
	private static TrackerServer  trackerServer;
	private static StorageServer  storageServer;
	private static StorageClient  storageClient;

	public FastDFSManager() {
		try {
			ClientGlobal.init(path);
			trackerClient = new TrackerClient();
			trackerServer = trackerClient.getConnection();
			storageClient = new StorageClient(trackerServer, storageServer);
			
		} catch (Exception e) {
			logger.error(e);

		}
	}
	public static FastDFSManager getInstance(){
		return FastDFSManagerHolder.instance;
	}

	public Map<String, String> upload(String uploadFilePath)
			throws IOException, MyException, NoSuchAlgorithmException {

		Map<String, String> retMap = new HashMap<String, String>();
		NameValuePair[] metaList = new NameValuePair[4];
		metaList[0] = new NameValuePair("width", "800");
		metaList[1] = new NameValuePair("heigth", "600");
		metaList[2] = new NameValuePair("bgcolor", "#FFFFFF");
		metaList[3] = new NameValuePair("author", "Mike");
		String[] results = storageClient.upload_appender_file(uploadFilePath,
				"zip", metaList);
		if (results != null) {

			String fileId;
			int ts;
			String token;
			StringBuffer fileUrl = new StringBuffer();
			InetSocketAddress inetSockAddr;

			String groupName = results[0];
			String remoteFilename = results[1];
			fileId = groupName
					+ StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR
					+ remoteFilename;

			inetSockAddr = trackerServer.getInetSocketAddress();
			fileUrl.append("http://").append(
					inetSockAddr.getAddress().getHostAddress());
			if (ClientGlobal.g_tracker_http_port != 80) {
				fileUrl.append(":").append(ClientGlobal.g_tracker_http_port);
			}
			fileUrl.append("/").append(fileId);
			if (ClientGlobal.g_anti_steal_token) {
				ts = (int) (System.currentTimeMillis() / 1000);
				token = ProtoCommon.getToken(fileId, ts,
						ClientGlobal.g_secret_key);
				fileUrl.append("?token=").append(token).append("&ts=")
						.append(ts);
			}

			logger.info(String.format("groupName: %s, remoteFilename: ",
					groupName, remoteFilename));
			logger.info(String.format("fileInfo: %s",
					storageClient.get_file_info(groupName, remoteFilename)));
			logger.info(String.format("file url: %s", fileUrl));

			retMap.put("groupName", groupName);
			retMap.put("remoteFileName", remoteFilename);
			retMap.put("downloadUrl", fileUrl.toString());
		}
		return retMap;
	}
	
	public void deleteFile(String groupName, String remoteFileName)
			throws IOException, MyException {
		long startTime = System.currentTimeMillis();
		int error = storageClient.delete_file(groupName, remoteFileName);
		logger.info(String.format("delete file time used: %s",
				System.currentTimeMillis() - startTime));
		if (error == 0) {
			logger.info("delete file success!");
		} else {
			logger.error(String.format("delete file fail, error no: %s", error));
		}
	}
	
	private static class FastDFSManagerHolder{
		public final static FastDFSManager instance = new FastDFSManager();
	}
	
	public static void main(String[] args) throws NoSuchAlgorithmException, IOException, MyException{
//		System.out.println(path);
		System.out.println(new FastDFSManager().upload("D:/webcrawl/113.119.132.1118088node1-13391656839059.zip"));
//		new FastDFSManager().deleteFile("group1", "M00/00/37/rBAB81PnHTCEXcJ2AAAAAFawqjk463.zip");
	}
}
